package servlet.user;

import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        int userid = Integer.parseInt(req.getParameter("user_id"));
        String password = req.getParameter("password");
        int role=Integer.parseInt(req.getParameter("role"));
        UserService us=new UserService();
        if(us.login(userid,password,role)){
            if(role==1){
                session.setAttribute("zhi",userid);
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().print("<script language='javascript'>  \n" +
                        "    alert('管理员，欢迎你！！！');  \n" +
                        "    window.location.href = 'first_admin.jsp';  \n" +
                        "</script>");
            }else {
                session.setAttribute("zhi",userid);
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().print("<script language='javascript'>  \n" +
                        "    alert('欢迎你，请尽情购物！');  \n" +
                        "    window.location.href = 'first.jsp';  \n" +
                        "</script>");
            }
        }else {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().print("<script language='javascript'>  \n" +
                    "    alert('密码错误，请重新输入密码！');  \n" +
                    "    window.location.href = 'first.jsp';  \n" +
                    "</script>");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

}
